package net.chenlin.dp.modules.sys.dingtalk;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiSsoGettokenRequest;
import com.dingtalk.api.request.OapiSsoGetuserinfoRequest;
import com.dingtalk.api.response.OapiSsoGettokenResponse;
import com.dingtalk.api.response.OapiSsoGetuserinfoResponse;
import com.mysql.jdbc.StringUtils;
import com.taobao.api.ApiException;

import net.chenlin.dp.common.support.ehcache.EhcacheManager;
import net.chenlin.dp.modules.sys.entity.SysUserEntity;
import net.sf.ehcache.Element;

public class DingtalkUtils {

	public DingtalkUtils() {
		// TODO Auto-generated constructor stub
	}

	private static String LINK_TYPE="DD";  //钉钉外部登录的标识。
	private static String ACCESS_TOKEN="DD_ACCESS_TOKEN";  //钉钉外部登录的标识。
	
	/**
	 * 
	 * @param corpid 公司ID
	 * @param ssoSecret 
	 * @return 访问令牌
	 * @throws ApiException
	 */
	public static String getAccessToken(String corpid, String ssoSecret) throws ApiException {
		
		Element objToken= EhcacheManager.getDingTalkCache().get(ACCESS_TOKEN);
		String token= objToken ==null ? null:objToken.getObjectValue().toString();
		
		if (StringUtils.isNullOrEmpty(token)) {
			DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sso/gettoken");
			OapiSsoGettokenRequest request = new OapiSsoGettokenRequest();
			request.setCorpid(corpid);
			request.setCorpsecret(ssoSecret);
			request.setHttpMethod("GET");
			OapiSsoGettokenResponse response = client.execute(request);
			token=response.getAccessToken();
			
			EhcacheManager.getDingTalkCache().put(new Element(ACCESS_TOKEN, token));
		}
		return token;
	}


	public static OapiSsoGetuserinfoResponse getUserInfo(String accessToken, String code) throws ApiException {
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sso/getuserinfo");
		OapiSsoGetuserinfoRequest request = new OapiSsoGetuserinfoRequest();
		request.setCode(code);
		request.setHttpMethod("GET");
		OapiSsoGetuserinfoResponse response = client.execute(request,accessToken);
		
		return response;
	}


	/**
	 * 
	 * @param dingtalkUserinfo
	 * @return
	 */
	public static SysUserEntity getOrSaveSysUser(OapiSsoGetuserinfoResponse dingtalkUserinfo) {
		//1.先判断是否已经存在
		
		
		
		
		return null;
	}

	
	
	
}
